export default {
  register:{
    /**
     * 注册监听刷新事件
     * @param that 组件的this
     * @param callback 回调刷新自己
     */
    watch:function (that,callback){
      var _t = that;
      _t.$nextTick(function(){//虚拟dom转化为真实dom后触发
        var pageVue = window.MC ? window.MC['vue'] : window.vueMc;
        if(typeof pageVue !='undefined' && pageVue && _t.mcWatch){
          var watch = _t.mcWatch;
          if(watch){
            var watchVars = watch.trim().split(",");
            for(var n=0;n<watchVars.length;n++){
              var varName = watchVars[n];
              pageVue.$watch(varName,function(n,o){
                callback();
              },{deep:true});
            }
          }
        }
      })
    }
  },
  util:{
    addScrollEvent:function (eventHandler) {
      if(window.iframeUi){
        window.addEventListener("scroll",eventHandler,true)
      }
    },
    removeScrollEvent:function (eventHandler) {
      if(window.iframeUi){
        window.removeEventListener('scroll',eventHandler,true);
      }
    },
    isInWindowView:function(ele){
      if(!window.iframeUi){
        return true;//生产环境 统一渲染 不用懒加载
      }
      if(!document.getElementById("magicalDragScene")){
        return true;
      }
      // console.log(ele)
      var rootRect = document.getElementById("magicalDragScene").getBoundingClientRect();
      var lt = {x:rootRect.x,y:rootRect.y}
      var rt = {x:rootRect.x+rootRect.width,y:rootRect.y}
      var lb = {x:rootRect.x,y:rootRect.y+rootRect.height}
      var rb = {x:rootRect.x+rootRect.width,y:rootRect.y+rootRect.height}
      // console.log(rootRect)

      var elRect= ele.getBoundingClientRect();
      if(elRect.width==0&&elRect.height==0){
        return false;
      }
      var elt = {x:elRect.x,y:elRect.y}
      var ert = {x:elRect.x+elRect.width,y:elRect.y}
      var elb = {x:elRect.x,y:elRect.y+elRect.height}
      var erb = {x:elRect.x+elRect.width,y:elRect.y+elRect.height}

      // console.log(elRect)
      if(elt.x>=lt.x && elt.x<=rt.x && elt.x>=lb.x &&elt.x<=rb.x
        && elt.y>=lt.y && elt.y>=rt.y && elt.y<= lb.y  && elt.y<=rb.y
      ){
        return true;
      }
      if(ert.x>=lt.x && ert.x<=rt.x && ert.x>=lb.x &&ert.x<=rb.x
        && ert.y>=lt.y && ert.y>=rt.y && ert.y<= lb.y  && ert.y<=rb.y){
        return true;
      }
      if(elb.x>=lt.x && elb.x<=rt.x && elb.x>=lb.x &&elb.x<=rb.x
        && elb.y>=lt.y && elb.y>=rt.y && elb.y<= lb.y  && elb.y<=rb.y){
        return true;
      }
      if(erb.x>=lt.x && erb.x<=rt.x && erb.x>=lb.x &&erb.x<=rb.x
        && erb.y>=lt.y && erb.y>=rt.y && erb.y<= lb.y  && erb.y<=rb.y){
        return true;
      }
      //这种情况是 比视窗大的时候
      if(elt.y<lt.y && elb.y>lb.y){
        return true;
      }
      return false;
    },
    findMcId:function(dom,attrName){
      if(window.iframeUi&&window.iframeUi.jsonFactory){
        var magicalCoderIdAttrName = window.iframeUi.jsonFactory.api().getMagicalCoderIdAttrName();
        var $el = $(dom);
        var mcid = $el.attr(attrName?attrName:magicalCoderIdAttrName);
        if(mcid){
          return mcid;
        }
      }
      return null;
    },
    addMcExtraToList:function (list) {
      if(list && list.length>0){
        for(var i=0;i<list.length;i++){
          var mcExtra = list[i]._mcExtra||{};
          this.addMcExtra(mcExtra);
          list[i]._mcExtra = mcExtra;
        }
      }
      return list;
    },
    //搞点状态给用户使用
    addMcExtra:function (extra) {
      extra.visible=false;
      extra.v1=false;
      extra.v2=false;
      extra.v3=false;
      extra.v4=false;
      extra.v5=false;
      extra.v6=false;
      extra.v7=false;
      extra.v8=false;
      extra.v9=false;
      extra.v10=false;
      extra.disabled=true;
      extra.d1=true;
      extra.d2=true;
      extra.d3=true;
      extra.d4=true;
      extra.d5=true;
      extra.d6=true;
      extra.d7=true;
      extra.d8=true;
      extra.d9=true;
      extra.d10=true;
    },
    /**
     * 新增一行
     * @param entity 初始化
     * @param index  要添加的行索引
     */
    addRow:function (tableData,entity,index){
      entity = entity||{}
        if(typeof index!='undefined'){
          tableData.splice(index,0,entity)
        }else {
          entity._mcExtra={}
          this.addMcExtra(entity._mcExtra);
          tableData.push(entity)
        }
    },
    deleteRow:function (tableData,index){
      if(tableData && tableData.length>0){
        if(typeof index!='undefined'){
          var delRow = tableData.splice(index,1);
          return delRow[0];
        }else {
          return tableData.pop();
        }
      }
      return null;
    },
    afterQuery:function(_t,data,successMsg){
      if(data){
        if(typeof data['code']!== 'undefined' && data.code===0){
          if(successMsg){
            _t.$message({message:successMsg,type:"success"});
            return true;
          }
        }else{
          if(data['desc']){
            _t.$message.error(data.desc);
            return false;
          }
        }
      }
      return true;
    },
    dealResult:function (vue,bindListName,cacheListName, res) {
      if(res.data){
        vue.$emit("before-render-data",{res:res});
        var resData = res.data;
        if(!Array.isArray(resData)){
          resData = [resData];//如果返回的数据不是数组，那么我们转成一维数组 这样就可以兼容更多场景的api接口
        }
        this.addMcExtraToList(resData);
        if(!window.iframeUi){
          vue[bindListName] = resData;
        }else {//设计阶段仅展示一条数据
          if(resData.length>0){
            vue[cacheListName] = resData;
            vue[bindListName] = [resData[0]];
          }else {//构造一条数据
            vue[cacheListName] = this.addMcExtraToList([{}]);
            vue[bindListName] = this.addMcExtraToList([{}]);
          }
        }
      }
    },
    parent:{
        layer:function({title,area,content}){
          parent.layer.open({
            title:title||"一行的数据结构",
            type:1,
            offset:"lt",
            maxmin: true,
            area :area||["500px","300px"],
            shade :0,
            content:"<textarea style='width:98%;height:96%'>"+content+"</textarea><div></div>"
          })
        }
    },
    /**
     * 搜索组件 只搜1个
     * @param {*} fromVueComponent
     * @param {*} query{tagName:"标签名正则"}
     * @returns {}
     */
    searchNode:function(fromVueComponent,query){
      var nodes = []
      this._searchNodes(nodes,fromVueComponent,query,1)
      if(nodes.length>0){
        return nodes[0]
      }
      return null;
    },
    /**
     * 搜索组件
     * @param {*} fromVueComponent
     * @param {*} query {tagName:"标签名正则"}
     * @param limit 最多搜索多少个
     * @returns []
     */
    searchNodes:function(fromVueComponent,query,limit){
      var nodes = []
      this._searchNodes(nodes,fromVueComponent,query,limit)
      return nodes;
    },
    _searchNodes:function (nodes,fromVueComponent,query,limit) {
      if(nodes.length==limit){
        return;
      }
      if(this.matchNode(fromVueComponent,query)){
          nodes.push(fromVueComponent);
      }
      if(nodes.length==limit){
        return;
      }
      var children = fromVueComponent.$children;
      if(children.length>0){
          for(var i=0;i<children.length;i++){
            if(nodes.length==limit){
              return;
            }
              this._searchNodes(nodes,children[i],query,limit);
          }
      }
    },
    matchNode:function(vueComponent,query){
        var tagName = query.tagName;
        var vnode=vueComponent.$vnode;
        if(tagName && vnode && vnode.tag){
          if(vnode.tag.match(new RegExp("vue-component-\\d+-"+tagName,"gi"))){
            return true;
          }
        }
        return false;
      },
    ajaxQuery:function (vueInstance,mcConfig,callback) {
      var _t = vueInstance;
      var request = _t.$magicaltool.request;
      if(mcConfig && mcConfig.url){
        var url = mcConfig.url;
        var method = mcConfig.method||'post';
        var limit = mcConfig.limit||20;
        var param = {};
        var ncv = request.util.collectMcNameCompareValue(_t);
        if(request.util.isMcQueryUrl(url) || request.util.isContentTypeJson(mcConfig.contentType)){
          param = request.util.paramsTomMcQuery(ncv || mcConfig.params);
          if(mcConfig.fields && mcConfig.fields.length>0){
            param.fields = mcConfig.fields
          }
          url += url.indexOf("?")!=-1 ? "&" : "?";
          url += "limit="+limit;
          param.order = request.util.mcQueryOrder(mcConfig.orders);
        }else{
          param = request.util.paramsToJson(ncv || mcConfig.params);
          param.limit = limit;//加个关键词入参
        }
        //keepUrl:true,
        request.axios({contentType:mcConfig.contentType,cache:true,$vue:_t,url:url,method:method,param:param}).then(function(res){
          if(callback){
            callback(res);
          }
        })
      }
    },
    //数组转树 data:[] idName:"id" pidName:"pid"
    arrayToTree:function(data,idName,pidName) {
      if(!data){
        return data;
      }
      data = JSON.parse(JSON.stringify(data))
      idName = idName||'id';
      pidName=pidName||"parentId";
      var  result = []
      var map = {}
      if (!Array.isArray(data)) {//验证data是不是数组类型
        return []
      }
      data.forEach(item => {map[item[idName]] = item})
      data.forEach(item => {
        var parent = map[item[pidName]] //找到data中每一项item的爸爸
        if (parent) {//说明元素有爸爸，把元素放在爸爸的children下面
          (parent.children || (parent.children = [])).push(item)
        } else {//说明元素没有爸爸，是根节点，把节点push到最终结果中
          result.push(item) //item是对象的引用
        }
      })
      return result //数组里的对象和data是共享的
    },
    treeToArray:function (node,idName,pidName) {
      if(!node){
        return node;
      }
      idName = idName||'id';
      pidName = pidName||"parentId";
      node = JSON.parse(JSON.stringify(node));
      var queue = node;
      if(!Array.isArray(node)){
        queue = [node];
      }
      var data = [] //返回的数组结构
      while (queue.length !== 0) { //当队列为空时就跳出循环
        var item = queue.shift() //取出队列中第一个元素
        var pid = item[idName]
        data.push(item)
        var children = item.children // 取出该节点的孩子
        if (children) {
          delete  item.children;
          for (var i = 0; i < children.length; i++) {
            var child = children[i];
            child[pidName] = pid;
            queue.push(child) //将子节点加入到队列尾部
          }
        }
      }
      return data;
    },
    transeKVType:function (val,originResults,kName,vName) {
      var vtype = typeof val;
      var newResults = [];
      for(var n=0;n<originResults.length;n++){
        var item = originResults[n];
        var k = item[kName];
        //自动兼容下 用户配置错误类型
        if(typeof k !== vtype){//类型不同 帮用户智能转换
          if(vtype==='number'){
            try {
              k = Number(k);
            }catch (e){
              console.log(e)
              k = item[kName];
            }
          }else if(vtype === 'string'){
            k = k+"";
          }
        }
        newResults.push({k:k,v:item[vName],row:item});
      }
      return newResults;
    },
    extend:function () {

    },
    elFormValidate:function (parentComponent,vue,callback) {
      var elForm = this.searchNode(parentComponent,{tagName:"elform"});
      if(elForm && elForm.model){
        elForm.validate(function(valid){
          if (!valid) {
            vue.$message.error("请检查表单校验规则");
            return false;
          }else{
            callback()
          }
        });
        return;
      }
      callback();
    },
    refreshDragEvent:function (vue) {
      if(window.iframeUi) {
        vue.$nextTick(function () {//虚拟dom转化为真实dom后触发 这样动态新增的结构里 仍然可以被拖拽
          if(window.iframeUi.magicalApi){
            window.iframeUi.magicalApi.addApiTask({methodName:"refreshDragEvent"});
          }
        })
      }
    },
    pubGenerateClearUUID:function () {
      var d = new Date().getTime();
      var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
      });
      return uuid.replace(/-/g,"");
    }
  }

};
